<template>
<div>
    <cube-page :title="this.course.title" ref="cubePage" />

    <!-- <div
      id="testVideo"
      class="video"
      playsinline="true"
      wekit-playsinline="true"
    ></div> -->
    <video ref="playerContainerId" class="video" preload="auto" playsinline webkit-playsinline></video>
    <!-- <canvas id="videoCanvas" class="video" /> -->

    <div class="cube-tab-bar">
        <div class="cube-tab" @click="selectTab(0)">
            <div :class="this.tabIndex == 0 ? 'selected' : ''">课程简介</div>
        </div>
        <div class="cube-tab" @click="selectTab(1)" v-if="isLive()">
            <div :class="this.tabIndex == 1 ? 'selected' : ''">留言板</div>
        </div>
    </div>

    <div class="view-wrapper">
        <div class="teacher-intro-b" v-if="this.tabIndex == 0">
            <h4 v-if="isLive()">直播时间</h4>
            <p v-if="isLive()">
                {{ this.course.startTime | dateFormat("yyyy-MM-dd hh:mm") }} ~
                {{ this.course.endTime | dateFormat("hh:mm") }}
            </p>

            <h4><span class="cubeic-person"></span>讲师</h4>
            <p>{{ this.course.author }}</p>

            <h4><span class="cubeic-hot"></span>课程概要</h4>
            <p v-html="this.course.summary"></p>
            <template v-if="!isLive()">
                <h4><span class="cubeic-calendar"></span> 历史学习时间 (进度:{{course.progress}}%)</h4>
                <div class="history">
                    <div v-for="(item,idx) in tableData" :key="idx">
                      <span class="cubeic-time"></span>  {{item.createTime| formatDataTime}}
                    </div>
                </div>
            </template>
        </div>

        <div class="message" v-if="this.tabIndex == 1">
            <div id="messageContainer" class="content">
                <!-- <div class="scroll"> -->
                <pull-to :top-load-method="refresh" class="scroll" :top-config="topConfig" id="messageScroll">
                    <ul class="list">
                        <div v-for="(item, index) in messageList" :key="index">
                            <li :class="isMe(item.userId) ? 'showTxt right' : 'showTxt left'">
                                {{ item.content }}
                                <div :class="
                      isMe(item.userId)
                        ? 'student rightName'
                        : 'student leftName'
                    ">
                                    {{ isMe(item.userId) ? "我" : item.nickName }}
                                </div>
                            </li>
                            <div style="clear: both"></div>
                        </div>
                    </ul>
                </pull-to>
                <!-- </div> -->
            </div>

            <div class="edit">
                <input v-model="messageContent" type="text" placeholder="请输入留言内容" class="txt" maxlength="140" @keyup.enter="sendMessage()" />
                <input @click="sendMessage()" type="button" name="" value="发送" class="btn" />
            </div>
        </div>
    </div>
</div>
</template>

<script>
import storage from "@/utils/storage";
import CubePage from "../components/cube-page.vue";
import PullTo from "vue-pull-to";
import {
    liveCourseSign,
    courseProgressUpdate,
    courseMesssageList,
    playCourse,
    findCoursePlayHistory
} from "../api/course";
import {
    MessageKey,
    EventManager,
    currentUser,
    currentCourse,
    liveCourseMsg,
    exitRoom,
} from "../api/message";
import coursestatus from "../enum/coursestatus";

export default {
    components: {
        CubePage,
        PullTo,
    },
    data() {
        return {
            messageContent: "",
            messageList: [],
            messageLength: 100,
            course: {},
            tabIndex: 0,
            isVodFinish: false,
            tableData: [],
            topConfig: {
                pullText: "下拉加载更多",
                triggerText: "释放开始加载",
                loadingText: "加载中...",
                doneText: "加载完成",
                failText: "加载失败",
                // 加载完后停留的时间ms
                loadedStayTime: 500,
                // 触发刷新后停留的距离
                stayDistance: 30,
                // 下拉刷新触发的距离
                triggerDistance: 40,
            },
        };
    },
    created() {
        this.course = this.$route.query.course;
        if (!this.course.id || typeof this.course.id == "undefined") {
            console.log("get course info from storage . ..");
            this.course = storage.getObj(storage.kStorageCourseInfo);
        } else {
            storage.setObj(storage.kStorageCourseInfo, this.course);
        }
        this.loadData()
    },
    mounted() {
        // console.log(this.$route.query.course);
        // this.course = this.$route.query.course;

        if (!this.course || !this.course.id) {
            this.$refs.cubePage.back();
        } else {
            this.play();
            if (this.isLive()) {
                this.registerEvent();
                this.liveCourseSign();
            } else {
                if (this.course.progress >= 99) {
                    this.setVodFinish();
                } else {
                    this.createrTimer();
                }
            }
            this.loadCourseMessage();
        }
    },
    beforeDestroy() {
        this.stop();
    },
    methods: {
        loadData() {
            findCoursePlayHistory(this.course.id, 1, 50).then(res => {
                this.tableData = res.data
            })
        },
        selectTab(index) {
            this.tabIndex = index;

            if (index == 1) {
                this.scrollToBottom();
            }
        },
        play() {
            var self = this
            console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! play", this.getVideoUrl());
            try {
                /* this.player = new window.Dvideo({
                          ele: "#testVideo",
                          poster: this.course.thumb,
                          showNext: false,
                          showHeader: false,
                          width: null,
                          height: null,
                          src: this.getVideoUrl(),
                          autoplay: true,
                          videoMode: this.isLive() ? 1 : 0, // 0:点播 2:直播
                          viewMode: 1,
                          progressCanDrag: true,
                          videoViewer: this.course.signCount
                        }); */
                this.player = TCPlayer(this.$refs.playerContainerId, {
                    autoplay: this.isLive(),
                }); // player-container-id 为播放器容器 ID，必须与 html 中一致
                this.player.src(this.getVideoUrl());
                this.player.on("play", function (error) {
                    // 做一些处理
                    self.seekToHistoryProgress();
                    self.videoLiveDownloadFinish();

                    if(this.isLive()){
                        return;
                    }
                    playCourse(self.course.id).then(res => {
                        console.log("------------------->play", res);
                    })
                });

            } catch (error) {
                console.error("!! play error.", error);
            }
        },
        stop() {
            if (this.player) {
                console.log("!! stop");
                // this.player.videoStop();
                this.player.pause()
                this.player.dispose()
            }
        },
        getVideoUrl() {
            return this.course.videoUrl;
        },
        isLive() {
            return this.course.status ? 1 : 0;
        },
        liveCourseSign() {
            liveCourseSign(this.course.id)
                .then((response) => {
                    console.log(response);
                })
                .catch((error) => {
                    console.log(error);
                    this.$toastErrorCode(error);
                });

            if (currentCourse.id == this.course.id) {
                // this.player.setVideoViewer(currentCourse.signCount);
            }
        },
        setVodFinish() {
            this.isVodFinish = true;
            this.player.setProgressCanDrag(this.isVodFinish);
        },
        vodProgressReport() {
            if (this.isVodFinish) return;

            let progress = Math.round(
                (this.player.currentTime() / this.player.duration()) * 100
            );

            if (progress >= 99) {
                progress = 100;
                this.setVodFinish();
            }

            courseProgressUpdate(this.course.id, progress)
                .then((response) => {
                    console.log(response);
                })
                .catch((error) => {
                    console.log(error);
                    this.$toastErrorCode(error);
                });
        },
        seekToHistoryProgress() {
            if (this.isLive()) return;
            if (this.course.progress <= 0 || this.course.progress >= 99) return;

            this.player.videoOnReadyToPlay = (durationT) => {
                var currentT = Math.floor((this.course.progress / 100.0) * durationT);
                this.player.seekTo(currentT);
                this.course.progress = 0;
            };
        },
        videoLiveDownloadFinish() {
            if (!this.isLive()) return;

            var timer = null;
            this.player.videoOnPlaying = () => {
                if (timer) {
                    clearInterval(timer);
                }
            };
            this.player.videoOnLiveFinish = () => {
                if (this.course.status != coursestatus.kCOURSE_STATUS_END) {
                    timer = setInterval(() => {
                        this.player.play();
                    }, 5000);
                }
            };
        },
        playStateChanged(data) {
            if (data && data.liveCoursePlayState.liveCourseId == this.course.id) {
                switch (data.liveCoursePlayState.playState) {
                    case coursestatus.kCOURSE_STATUS_PLAYING:
                        this.player.play();
                        break;
                    case coursestatus.kCOURSE_STATUS_END:
                        this.course.status = coursestatus.kCOURSE_STATUS_END;
                        this.showEndAlert();
                        break;
                    default:
                        break;
                }
            }
        },
        signCountChanged(data) {
            if (data && data.liveCourseSignCount.liveCourseId == this.course.id) {
                // this.player.setVideoViewer(data.liveCourseSignCount.signCount);
            }
        },
        refresh(loaded) {
            this.loadCourseMessage(loaded);
        },
        loadCourseMessage(loaded = null) {
            var lastMsgId = 0;
            if (this.messageList && this.messageList.length > 0) {
                if (this.messageList[0].id) {
                    lastMsgId = this.messageList[0].id;
                }
            }
            courseMesssageList(this.course.id, lastMsgId)
                .then((response) => {
                    if (response && response.data && response.data.length > 0) {
                        if (this.messageList && this.messageList.length > 0) {
                            this.messageList = response.data.concat(this.messageList);
                        } else {
                            this.messageList = response.data;
                        }
                    }

                    if (loaded) {
                        loaded("done");
                    }
                })
                .catch((error) => {
                    console.log(error);
                    this.$toastErrorCode(error);
                });
        },
        isMe(userId) {
            return userId == currentUser.userId ? 1 : 0;
        },
        receivedMessage(data) {
            if (
                data &&
                data.liveCourseMsg &&
                data.liveCourseMsg.liveCourseId &&
                data.liveCourseMsg.liveCourseId == this.course.id
            ) {
                var message = {};
                message.userId = data.userId;
                message.nickName = data.liveCourseMsg.nickName;
                message.content = data.liveCourseMsg.content;
                this.messageList.push(message);

                // 控制留言数据的条数
                // if (this.messageList.length > this.messageLength) {
                //   this.messageList.shift();
                // }

                // 清空输入框
                if (data.userId == currentUser.userId) {
                    this.messageContent = "";
                }

                // 滚动
                this.scrollToBottom();
            }
        },
        sendMessage() {
            if (!this.messageContent || this.messageContent.trim().length <= 0)
                return;

            liveCourseMsg(this.messageContent);
        },
        scrollToBottom() {
            this.$nextTick(() => {
                let msg = document.getElementsByClassName("scroll-container")[0]; // 获取对象
                if (msg && msg.scrollHeight) {
                    msg.scrollTop = msg.scrollHeight; // 滚动高度
                }
            });
        },
        showEndAlert() {
            this.$createDialog({
                type: "alert",
                title: "提示",
                content: "课程已经结束，休息下吧！",
                confirmBtn: {
                    text: "好的",
                    active: true,
                    href: "javascript:;",
                },
                onConfirm: () => {
                    this.$router.back();
                },
            }).show();
        },
        registerEvent() {
            EventManager.Register(
                MessageKey.liveCoursePlayState,
                this.playStateChanged.bind(this),
                this
            );
            EventManager.Register(
                MessageKey.liveCourseSignCount,
                this.signCountChanged.bind(this),
                this
            );
            EventManager.Register(
                MessageKey.liveCourseMsg,
                this.receivedMessage.bind(this),
                this
            );
            this.$once("hook:beforeDestroy", () => {
                EventManager.UnRegister(MessageKey.liveCoursePlayState, this);
                EventManager.UnRegister(MessageKey.liveCourseSignCount, this);
                EventManager.UnRegister(MessageKey.liveCourseMsg, this);

                exitRoom(this.course.id);
            });
        },
        createrTimer() {
            const timer = setInterval(() => {
                this.vodProgressReport();
            }, 10000);
            this.$once("hook:beforeDestroy", () => {
                clearInterval(timer);
            });
        },
    },
};
</script>

<style lang="stylus" scoped>
.video {
    width: 100%;
    height: calc((100vw * 10 / 16));
    background: #000;
}

.view-wrapper {
    position: fixed;
    top: calc(100vw * 10 / 16 + 44px + 35px);
    left: 0;
    bottom: 0;
    width: 100%;
    overflow: auto;

    .index-list-wrapper {
        height: 100%;
        width: 100%;
        margin: 0 auto;
        overflow: hidden;
    }
}

.teacher-intro-b {
    color: #5e5e5e;
    font: 14px / 2em 'PingFang SC', '微软雅黑', 'Microsoft YaHei', Helvetica, 'Helvetica Neue', Tahoma, Arial, sans-serif;
    font-size: 24px;
    -webkit-tap-highlight-color: transparent;
    margin: 0;
    background: #FFF;
    padding: 0.64rem;
    line-height: 30px;
}

.teacher-intro-b h4 {
    color: #2B333B;
    font-size: 0.37333333rem;
    margin-bottom: 0.21333333rem;
    font-weight: 600;
}

.lecturer-list {
    margin-bottom: 0.64rem;
}

.clearfix {
    @css {
        *
    }

    zoom: 1;
}

.teacher-intro-b p {
    font-size: 24px;
}

.teacher-intro-b p {
    font-size: 12px;
    color: #71777D;
    line-height: 0.48rem;
    margin-bottom: 24px;
}

.cube-tab-bar {
    border-bottom: 1px solid #eee;
}

.cube-tab {
    font-size: 16px;
    line-height: 20px;
    color: #999;
}

.cube-tab .selected {
    font-weight: 600;
    color: #E8864D;
}

.pulldown-content {
    font-size: 14px;
}

.message {
    margin: 0 auto;
    position: relative;
    height: 100%;
    font-size: 14px;
}

.message .content {
    height: calc(100% - 45px);
    overflow-y: auto;
    margin-bottom: 5px;
}

.message .content .scroll {
    position: relative;
}

.message .content .scroll ul {
    margin: 0;
    padding: 0;
}

.message .edit {
    background: #ece7e766;
    height: 40px;
}

.message .txt {
    margin-top: 3px;
    margin-left: 3px;
    position: absolute;
    border-radius: 2px;
    border: 1px solid #ccc;
    height: 30px;
    width: calc(100% - 88px);
    border-radius: 0;
    box-shadow: none;
    border-color: #d2d6de;
    font-size: 14px;
    line-height: 14px;
    padding: 0 5px;
}

.message .btn {
    margin-top: 3px;
    right: 3px;
    position: absolute;
    background-color: #00c0ef;
    border-color: #00acd6;
    padding: 6px 20px;
    font-size: 14px;
    line-height: 1.42857143;
    color: #fff;
}

.message .showTxt {
    width: auto;
    height: auto;
    max-width: 290px;
    background: #d2d6de;
    border: 0;
    font-size: 15px;
    color: #444;
    padding: 5px 10px;
    border-radius: 2px;
    word-break: break-all;
    list-style: none;
    margin-top: 30px;
    display: list-item;
    position: relative;
}

.message .left {
    text-align: left;
    margin-left: 20px;
    float: left;
}

.message .right {
    text-align: left;
    margin-right: 20px;
    float: right;
    background: #f39c12;
    color: #fff;
}

.message .student {
    color: #999;
    text-overflow: clip;
    font-size: 12px;
    font-weight: 600;
    white-space: nowrap;
    overflow: hidden;
    line-height: 16px;
    top: -18px;
}

.message .leftName {
    left: -0.5px;
    position: absolute;
}

.message .rightName {
    right: -0.5px;
    position: absolute;
}

input[type='button'],
input[type='submit'],
input[type='reset'] {
    -webkit-appearance: none;
}

.history-title {
    font-size: 12px;
}

.history {
    font-size: 12px;
}
</style>
